package xnj.lazydog.btcontroller.ControlViews.ControlViews;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.ColorDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.text.DecimalFormat;

import xnj.lazydog.btcontroller.ControlViews.ControlView;
import xnj.lazydog.btcontroller.ControlViews.Value;
import xnj.lazydog.btcontroller.ControlViews.ViewOptions;
import xnj.lazydog.btcontroller.R;

public class ControlEditText extends ControlElement {

    float EDGE_MIN_MM = 0.2f;
    float EDGE_MAX_MM = 2;
    float edge_max_pix;
    float edge_min_pix;
    float TEXT_SIZE_RATIO = 0.5f;

    DecimalFormat decimalFormat;

    public ControlEditText(ViewOptions options) {
        super(options);

        decimalFormat = new DecimalFormat("##.####");
        edge_max_pix = ControlView.mm2Pix(EDGE_MAX_MM);
        edge_min_pix = ControlView.mm2Pix(EDGE_MIN_MM);
        p.setTextAlign(Paint.Align.CENTER);
        p.setColor(THEME_TEXT_DARK_COLOR);
        settingsAfterLink = false;
    }


    @Override
    public void showSettingsDialog(Context context) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        AlertDialog dialog = builder.setView(R.layout.toy_settings_edit_text).create();

        if(dialog.getWindow()!=null)
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        dialog.show();
    }

    RectF rect = new RectF();
    RectF rRect = new RectF();

    float EDGE_RATIO = 0.01f;
    float edge_pix;
    float edge_pix_half;


    @Override
    public void onSizeChanged() {
        text_height_pix = h_pix * TEXT_SIZE_RATIO;

        if (text_height_pix > max_text_pix)
            text_height_pix = max_text_pix;
        if (text_height_pix < min_text_pix)
            text_height_pix = min_text_pix;

        if (Math.abs(text_height_pix - last_text_height_pix) > 8) {
            p.setTextSize(text_height_pix);
            last_text_height_pix = text_height_pix;
        }
        text_y_pix = text_height_pix * 0.36f;

        rect.left = -w_pix * 0.5f;
        rect.right = w_pix * 0.5f;
        rect.top = -h_pix * 0.5f;
        rect.bottom = h_pix * 0.5f;

        edge_pix = (w_pix + h_pix) * EDGE_RATIO;

        if (edge_pix > edge_max_pix)
            edge_pix = edge_max_pix;
        if (edge_pix < edge_min_pix)
            edge_pix = edge_min_pix;

        edge_pix_half = edge_pix * 0.5f;

        rRect.left = rect.left + edge_pix_half;
        rRect.right = rect.right - edge_pix_half;
        rRect.top = rect.top + edge_pix_half;
        rRect.bottom = rect.bottom - edge_pix_half;


        p.setStrokeWidth(edge_pix);

    }


    @Override
    public void draw(Canvas canvas) {

        canvas.save();
        canvas.clipRect(rect);


        p.setStyle(Paint.Style.FILL);
        p.setColor(0xffffffff);

        canvas.drawRect(rRect.left, rRect.top, rRect.right, rRect.bottom, p);
        p.setColor(THEME_TEXT_DARK_COLOR);

        if (linkedValues[0] == null) {
            canvas.drawText("文本框", 0, text_y_pix, p);
        } else {
            canvas.drawText(valuesName[0] + " : " + decimalFormat.format(linkedValues[0].get()), 0, text_y_pix, p);
        }


        p.setStyle(Paint.Style.STROKE);
        p.setColor(ViewOptions.THEME_EDGE_COLOR);
        canvas.drawRoundRect(rRect, edge_pix, edge_pix, p);
        //canvas.drawRect(rRect,p);
        canvas.restore();
    }

    private static final String TAG = "ControlEditText";

    void initNumberInputSuite(final EditText editText, final TextView textView, final Value value, final String name) {

        final Value value1 = new Value(value.type);


        final float max,min;


        switch (value1.type)
        {
            case 0:
                max = 1;
                min = 0;


                break;
            case 1:
                max = 127;
                min =-128;

                break;
            case 2:
                max = 32767;
                min = -32768;

                break;
            case 3:
                max = Integer.MAX_VALUE;
                min = Integer.MIN_VALUE;

                break;
            case 4:
                max = Float.MAX_VALUE;
                min = -Float.MAX_VALUE;

                break;
                default:
                    max = 1;
                    min = 0;
        }
        String str = "设置"+name+"的值";

        //Log.w(TAG, "initNumberInputSuite:"+max+"  "+min);
        textView.setText(str);


        if(value.type>0) {
            str = "" + value.get();
        }
        else
            str = ""+(value.getBoolean()?1:0);

        editText.setText(str);


        editText.setSelection(str.length());

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                float number;

                if(s.toString().equals("")||s.toString().equals("-"))
                    return;

                try {
                    number = Float.parseFloat(s.toString());
                }catch (NumberFormatException e)
                {
                    number = 0;
                    editText.setText("");
                    editText.setSelection(0);
                }

                if(number>max)
                {
                    String v_str;

                    if(value1.type==4)
                        v_str = ""+max;
                    else
                        v_str = ""+((int)max);

                    String str = v_str;
                    editText.setText(str);
                    editText.setSelection(str.length());
                    str = name+"的类型为"+type_name[value1.type]+",取值不得大于"+v_str;
                    textView.setText(str);
                    ControlView.bigSmall(textView);
                }
                if(number<min)
                {
                    String v_str;
                    if(value1.type==4)
                        v_str = ""+min;
                    else
                        v_str = ""+((int)min);

                    String str = v_str;
                    editText.setText(str);
                    editText.setSelection(str.length());
                    str = name+"的类型为"+type_name[value1.type]+",取值不得小于"+v_str;
                    textView.setText(str);
                    ControlView.bigSmall(textView);
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }


    void showEditDialog(final Context context)
    {
        Button cancel,confirm;
        final TextView textView;
        final EditText editText;

        View view = LayoutInflater.from(context).inflate(R.layout.toy_edit_text_value,null);

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setView(view);
        final AlertDialog dialog = builder.create();

        if(dialog.getWindow()!=null)
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        textView = view.findViewById(R.id.value_info);
        editText = view.findViewById(R.id.toy_edit_text);
        cancel = view.findViewById(R.id.toy_edit_cancel_button);
        confirm = view.findViewById(R.id.toy_edit_confirm_button);

        initNumberInputSuite(editText,textView,linkedValues[0],valuesName[0]);

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                float number;
                float max = MAX_VALUES[linkedValues[0].type];

                float min = MIN_VALUES[linkedValues[0].type];

                try {
                    number = Float.parseFloat(editText.getText().toString());
                }catch (NumberFormatException e)
                {
                    number = 0;
                    editText.setText("0");
                }
                if(number>max)
                {
                    String str = ""+max;
                    editText.setText(str);
                    str = valuesName[0]+"的类型为"+type_name[linkedValues[0].type]+",取值不得大于"+max;
                    textView.setText(str);
                    number = max;
                }
                if(number<min)
                {
                    String str = ""+min;
                    editText.setText(str);
                    str = valuesName[0]+"的类型为"+type_name[linkedValues[0].type]+",取值不得小于"+min;
                    textView.setText(str);
                    number = min;
                }

                if(!data_dir_tx[0])
                    Toast.makeText(context,"该控件链接的是接收组变量，因此编辑无效",Toast.LENGTH_SHORT).show();
                else
                    linkedValues[0].set(number);
                triggerDataEvent();
                dialog.dismiss();
            }
        });

        dialog.show();
    }

    @Override
    public void clicked(Context context) {

        if(linkedValues[0]!=null)
            showEditDialog(context);
        else
            Toast.makeText(context,"该控件没有链接变量",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void dragged() {

    }

    @Override
    public void released() {

    }

    @Override
    public void pressed() {

    }

    @Override
    public void zoomed(float sx, float sy) {

    }

}
